package com.shuke.sk_worm.tool.hiskpi.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.shuke.sk_worm.Mapper.HisKpiMapper;
import com.shuke.sk_worm.consts.ShopPlatformEnum;
import com.shuke.sk_worm.domain.HisKpi;
import com.shuke.sk_worm.domain.SkAccountInfo;
import com.shuke.sk_worm.domain.SkRealData;
import com.shuke.sk_worm.dto.KuaishouHisKpiDto;
import com.shuke.sk_worm.dto.KuaishouHisKpiValueDto;
import com.shuke.sk_worm.dto.KuaishouRealDto;
import com.shuke.sk_worm.service.HisKpiService;
import com.shuke.sk_worm.service.SkRealDataService;
import com.shuke.sk_worm.service.SysUserService;
import com.shuke.sk_worm.tool.TimeUtil;
import com.shuke.sk_worm.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class KuaishouShopImpl extends ShopDataImpl{
    private String staffUrl = "https://im.kwaixiaodian.com/gateway/business/cs/get/data/center/reception/staff/list";

    private String hisDataUrl = "https://im.kwaixiaodian.com/gateway/business/cs/get/data/center/examine/detail";

    private String realDataUrl = "https://im.kwaixiaodian.com/gateway/business/get/cs/reception/merge/data";

    @Autowired
    private HisKpiService hisKpiService;

    @Autowired
    private SkRealDataService realDataService;

    private List<HisKpi> getUrlHisData(Date date, String cookie, List<String> shopAccounts, ShopInfoListVo shop){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Long timestamp = date.getTime();
        //将时间转换指定格式的日期
        String terDate = f.format(timestamp);

        Map<String, Object> body = new HashMap<>();

        body.put("pageSize", 100);
        body.put("pageNum", 1);
        body.put("elementType", 1);
        body.put("timeRange", "ONE_DAY");
        body.put("currentStartDay", sdf.format(date));
        body.put("currentEndDay", sdf.format(date));
        body.put("queryField", Arrays.asList( "threeMinReplyRate", "askBuyerNumManual",
                "askBuyerCntManual", "avgReplyDurManual", "manualSessionCnt", "sessionThreeMinReplyRate",
                "goodEvaluateRate", "badEvaluateRate", "normalEvaluateRate", "inviteEvaluateCnt",
                "evaluateCnt", "evaluateRate", "inviteEvaluateRate", "goodEvaluateCnt",
                "normalEvaluateCnt", "badEvaluateCnt", "sessionGoodEvaluateRate", "sessionBadEvaluateRate",
                "sessionNormalEvaluateRate", "evaluateSessionCnt", "inviteEvaluateSessionCnt", "noReplySessionRate",
                "askOrderPayOrderRate", "askOrderBuyerCnt", "askOrderPayOrderBuyerCnt", "askOrderPayOrderAmtView",
                "askOrderSingleBuyerValue"));
        String response =  HttpRequest.post(hisDataUrl).
                header("Cookie", cookie).
                contentType("application/json").
                body(JSONUtil.parseObj(body).toString()).
                execute().
                body();
        JSONObject jsonObject = JSONUtil.parseObj(response);
        List<HisKpi> hisKpis = new ArrayList<>();
        if ("1".equals(String.valueOf(jsonObject.get("result")))){
            JSONObject data = JSONUtil.parseObj(jsonObject.get("data"));
            System.out.print(data);
            List<KuaishouHisDataVo> hisDatas = JSONUtil.toList(JSONUtil.parseArray(data.get("detail")), KuaishouHisDataVo.class);
            System.out.print(hisDatas);
            for (KuaishouHisDataVo his : hisDatas) {
                if (shopAccounts.contains(his.getStaffName())){
                    KuaishouHisDataMapVo dataMapVo = his.getDataMap();
                    HisKpi hisKpi = new HisKpi();
                    hisKpi.setStaffName(his.getStaffName()); //客服昵称
                    hisKpi.setStaffUsername(his.getStaffName()); //子账号
                    hisKpi.setLaborUserAmount(Integer.valueOf(dataMapVo.getAskBuyerNumManual())); //人工已接待数量
                    hisKpi.setLaborAmount(Integer.valueOf(dataMapVo.getAskBuyerCntManual())); //人工已接待会话数
                    hisKpi.setDissatisfactionRate(dataMapVo.getBadEvaluateRate()); //不满意率
                    hisKpi.setThreeMinResponseConRate(dataMapVo.getSessionThreeMinReplyRate()); //三分钟人工回复率(3分钟人工回复率（会话）)
                    hisKpi.setSatisfactionRate(TimeUtil.subPercent(dataMapVo.getBadEvaluateRate())); //满意率
                    hisKpi.setThreeMinResponseRate(TimeUtil.dateConversion(dataMapVo.getThreeMinReplyRate()));//三分钟响应率(3分钟人工回复率（消息）)
                    hisKpi.setAvgResponseDuration(String.valueOf(Long.valueOf(dataMapVo.getAvgReplyDurManual()) / 1000));//新平均响应时长
                    hisKpi.setInquirerAmount(dataMapVo.getAskOrderBuyerCnt()); //询单人数
                    hisKpi.setPurchasersAmount(dataMapVo.getAskOrderPayOrderBuyerCnt()); //支付人数
                    hisKpi.setInquiryConversionRate(dataMapVo.getAskOrderPayOrderRate()); //询单转化率
                    hisKpi.setSalesAmount(dataMapVo.getAskOrderPayOrderAmtView()); //销售金额
                    hisKpi.setInsertTime(terDate);
                    hisKpi.setInsertTimestamp(timestamp);
                    hisKpi.setUserId(shop.getUserId());
                    hisKpi.setUserName(shop.getUserName());
                    hisKpi.setShopId(shop.getId());
                    hisKpi.setShopName(shop.getName());
                    hisKpi.setUserIds(shop.getUserIds());
                    hisKpi.setDeptId(shop.getDeptId());
                    hisKpi.setDeptIds(shop.getDeptIds());
                    hisKpi.setDeptNames(shop.getDeptNames());
                    hisKpi.setPlatform(ShopPlatformEnum.KUAISHOU);
                    hisKpi.setBusinessManagerIds(shop.getBusinessManagerIds());
                    hisKpi.setBusinessManagerNames(shop.getBusinessManagerNames());
                    hisKpi.setBaseManagerIds(shop.getBaseManagerIds());
                    hisKpi.setBaseManagerNames(shop.getBaseManagerNames());
                    hisKpis.add(hisKpi);
                }
            }
        }

        return hisKpis;
    }

    @Override
    public void hiskpi(List<ShopInfoListVo> shopInfoList, Map<Long,String> shopCookie, Date startTime){
        if (shopInfoList.isEmpty()){
            return;
        }

        for (ShopInfoListVo shop : shopInfoList) {
            if (!shopCookie.containsKey(shop.getId())) {
                logger.info("店铺ID :" + shop.getId() + "未获取到Token");
                continue;
            }

            //账号信息
            List<String> shopAccounts = shop.getAccountInfos().stream().map(vo->{
                return  vo.getShopAccount().trim();
            }).collect(Collectors.toList());


            //昨日的数据
            List<HisKpi> yesterData = getUrlHisData(startTime, shopCookie.get(shop.getId()), shopAccounts, shop);
            if (!yesterData.isEmpty()){
                hisKpiService.batchInsertData(yesterData);
            }

            //24小时前的数据
            Date fourDay = DateUtil.offsetDay(startTime, -1);
            List<HisKpi> fourData =  getUrlHisData(fourDay, shopCookie.get(shop.getId()), shopAccounts, shop);
            if (!fourData.isEmpty()){
                //保存数据
                hisKpiService.batchInsertData(fourData);
            }

            Date eightDay = DateUtil.offsetDay(fourDay, -1);
            List<HisKpi> eightData =  getUrlHisData(eightDay, shopCookie.get(shop.getId()), shopAccounts, shop);
            if (!eightData.isEmpty()){
                //保存数据
                hisKpiService.batchInsertData(eightData);
            }
        }
    }

    public List<KuaishouStaffInfoVo> getStaffs(String cookie){
        Date yester = DateUtil.offsetDay(DateUtil.beginOfDay(DateUtil.date()), -1);

        String pattern = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        List<KuaishouStaffInfoVo> staffInfoVos = new ArrayList<>();

        Map<String, Object> body = new HashMap<>();

        body.put("currentStartDay", sdf.format(yester));
        body.put("currentEndDay", sdf.format(yester));
        body.put("dateType", 7);
        String response = HttpRequest.post(staffUrl).
                header("Cookie", cookie).
                body(JSONUtil.parseObj(body).toString()).
                execute().body();

        JSONObject jsonObject = JSONUtil.parseObj(response);
        if ("1".equals(String.valueOf(jsonObject.get("result")))){
            JSONObject staffs = JSONUtil.parseObj(jsonObject.get("data"));
            staffInfoVos = JSONUtil.toList(JSONUtil.parseArray(staffs.get("staffList")), KuaishouStaffInfoVo.class);
        }
        return staffInfoVos;
    }

    @Override
    public void realData(List<ShopInfoListVo> shopInfoList, Map<Long,String> shopCookie){
        if (shopInfoList.isEmpty()){
            return;
        }

        for (ShopInfoListVo shop : shopInfoList){
            logger.info("Real_DATA: 店铺：" + shop.getName());
            Long nowTimeMillis = System.currentTimeMillis();  //时间戳

            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
            //将时间转换指定格式的日期
            String nowDate = f.format(nowTimeMillis);

            if (!shopCookie.containsKey(shop.getId())){
                logger.info("店铺ID :" + shop.getId() + "未获取到Token");
                continue;
            }

            //获取用户ID
            List<KuaishouStaffInfoVo> staffInfoVos = getStaffs(shopCookie.get(shop.getId()));

            Map<String, String> staffMap = new HashMap<>();

            staffInfoVos.forEach(v->{
                staffMap.put(v.getElementName(),v.getElementId());
            });

            List<SkRealData> realDatas = new ArrayList<>();
            for(SkAccountInfo account : shop.getAccountInfos()){
                if (!staffMap.containsKey(account.getShopAccount())){
                    continue;
                }

                Map<String, Object> body = new HashMap<>();

                body.put("serviceCode", "getCsRealTimeDataMergeServiceV2");

                KuaishouRealDto kuaishouRealDto = new KuaishouRealDto();

                KuaishouHisKpiValueDto valueDto1 = new KuaishouHisKpiValueDto();
                valueDto1.setValue(Arrays.asList(staffMap.get(account.getShopAccount())));
                kuaishouRealDto.setAssistantId(valueDto1);

                KuaishouHisKpiValueDto valueDto2 = new KuaishouHisKpiValueDto();
                valueDto2.setValue(Arrays.asList(nowDate));
                kuaishouRealDto.setDateStr(valueDto2);

                KuaishouHisKpiValueDto valueDto3 = new KuaishouHisKpiValueDto();
                valueDto3.setValue(Arrays.asList("staff"));
                kuaishouRealDto.setSource(valueDto3);

                body.put("param", kuaishouRealDto);

                String response = HttpRequest.post(realDataUrl).
                        header("Cookie", shopCookie.get(shop.getId())).
                        body(JSONUtil.parseObj(body).toString()).
                        execute().body();
                System.out.print(response);

                JSONObject jsonObject = JSONUtil.parseObj(response);

                if ("1".equals(String.valueOf(jsonObject.get("result")))){
                    List<KuaishouRealDataVo> realDataVos = JSONUtil.toList(JSONUtil.parseArray(jsonObject.get("data")), KuaishouRealDataVo.class);
                    SkRealData realData = new SkRealData();
                    realDataVos.forEach(vo->{

                        if ("seller_three_min_reply_rate".equals(vo.getKey()) && vo.getValue() != null){
                            realData.setThreeMinResponseRate(vo.getValue().getValue());
                            realData.setThreeMinResponseConRate(vo.getValue().getValue());
                        }

                        if ("seller_im_bad_evaluate_rate".equals(vo.getKey()) && vo.getValue() != null){
                            realData.setDissatisfactionRate(vo.getValue().getValue());
                        }

                        if ("avg_reply_time".equals(vo.getKey()) && vo.getValue() != null){
                            realData.setAvgResponseDuration(TimeUtil.dateConversion(vo.getValue().getValue()));
                        }

                        if ("ask_num".equals(vo.getKey()) && vo.getValue() != null){
                            realData.setLaborUserAmount(vo.getValue().getValue());
                        }

                        if ("ask_cnt".equals(vo.getKey()) && vo.getValue() != null){
                            realData.setEndChatNum(vo.getValue().getValue());
                        }
                    });
                    if (realData.getDissatisfactionRate() != null){
                        realData.setSatisfactionRate(TimeUtil.subPercent(realData.getDissatisfactionRate()));
                    }
                    realData.setStaffName(account.getShopAccount());
                    realData.setStaffUsername(account.getShopAccount());
                    realData.setUserId(shop.getUserId());
                    realData.setUserIds(shop.getUserIds());
                    realData.setUserName(shop.getUserName());
                    realData.setShopId(shop.getId());
                    realData.setShopName(shop.getName());
                    realData.setDeptId(shop.getDeptId());
                    realData.setInsertTimestamp(nowTimeMillis);
                    realData.setDeptIds(shop.getDeptIds());
                    realData.setDeptNames(shop.getDeptNames());
                    realData.setBusinessManagerIds(shop.getBusinessManagerIds());
                    realData.setBusinessManagerNames(shop.getBusinessManagerNames());
                    realData.setBaseManagerIds(shop.getBaseManagerIds());
                    realData.setBaseManagerNames(shop.getBaseManagerNames());
                    realData.setPlatform(ShopPlatformEnum.KUAISHOU);
                    realDatas.add(realData);
                }
            }
            if (!realDataService.saveBatch(realDatas)){
                logger.info(realDatas);
            }
        }
    }
}
